# _*_ coding:utf-8 _*_
import win32com
from win32com import client
import VBAPI
import os
from tkinter import *
from tkinter import ttk, messagebox, filedialog, scrolledtext
CREO_APP = 'C:/Program Files/PTC/Creo 6.0.4.0/Parametric/bin/parametric.exe'
INPUT_DIR = 'E:/python/test_data-3/'

win = Tk()
win.title("批量参数操作")
win.iconbitmap("./creologo.ico")
win.wm_attributes('-topmost', 1)
win.resizable(0, 0)

Label(win, text="Creo路径:", padx=5, pady=5).grid(row=0, column=0, sticky='W')
e1 = Entry(win, width="55")
e1.grid(row=0, column=1, columnspan=4, padx=5, pady=5)
e1.insert(0, CREO_APP)

Label(win, text="文件目录:", padx=5, pady=5).grid(row=1, column=0, sticky="W")
e2 = Entry(win, width="55")
e2.grid(row=1, column=1, columnspan=4, padx=5, pady=5)
e2.insert(0, INPUT_DIR)

Label(win, text="在此编辑参数:", padx=5, pady=5).grid(row=2, column=0, columnspan=3, sticky='W')
Label(win, text="参数名", padx=5, pady=5).grid(row=3, column=0)
e_paraname = Entry(win, width="15")
e_paraname.grid(row=3, column=1, padx=5, pady=5)

Label(win, text="参数值", padx=5, pady=5).grid(row=3, column=2)
e_paraval = Entry(win, width="15")
e_paraval.grid(row=3, column=3, padx=5, pady=5)

def set_defaultvalue(event):
    if e_paraname.get() != "":
        e_paraval.delete('0', 'end')
        e_paraval.insert('0', 0)


e_paraval.bind("<Button-1>", set_defaultvalue)


Label(win, text="参数类型", padx=5, pady=5).grid(row=3, column=4)
e_paratype = ttk.Combobox(win)
e_paratype.grid(row=3, column=5, padx=5, pady=5)
e_paratype["value"] = ("字符串", "浮点型", "整型", "布尔型")
e_paratype.current(0)

st_message = scrolledtext.ScrolledText(win, width=85, height=15)
st_message.grid(row=5, column=0, columnspan=6, padx=5, pady=5)

#添加/修改参数

def add_para():
    para_content = {"name": e_paraname.get(), "value": e_paraval.get(), "type": e_paratype.get()}
    ipara_content = {}
    try:
        if para_content['type'] == "字符串":
            ipara_content['value'] = client.Dispatch(VBAPI.CMpfcModelItem).CreateStringParamValue(para_content['value'])
        elif para_content['type'] == "浮点型":
            ipara_content['value'] = client.Dispatch(VBAPI.CMpfcModelItem).CreateDoubleParamValue(para_content['value'])
        elif para_content['type'] == "整型":
            ipara_content['value'] = client.Dispatch(VBAPI.CMpfcModelItem).CreateIntParamValue(para_content['value'])
        elif para_content['type'] == "布尔型":
            ipara_content['value'] = client.Dispatch(VBAPI.CMpfcModelItem).CreateBoolParamValue(para_content['value'])
        else:
            ipara_content['value'] = client.Dispatch(VBAPI.CMpfcModelItem).CreateNoteParamValue(para_content['value'])
    except ValueError as e:
        messagebox.showinfo(e)

    try:
        cAC = client.Dispatch(VBAPI.CCpfcAsyncConnection)
        AsyncConnection = cAC.Start(CREO_APP + ' -g:no_graphics -i:rpc_input', '')
        files = AsyncConnection.Session.ListFiles("*.prt", getattr(VBAPI.constants, "EpfcFILE_LIST_LATEST"), INPUT_DIR)
        for i in range(0, files.Count):
            ModelDescriptor = client.Dispatch(VBAPI.CCpfcModelDescriptor)
            mdlDescr = ModelDescriptor.Create(getattr(VBAPI.constants, "EpfcMDL_PART"), "", None)
            mdlDescr.Path = files.Item(i)
            RetrieveModelOptions = client.Dispatch(VBAPI.CCpfcRetrieveModelOptions)
            options = RetrieveModelOptions.Create()
            options.AskUserAboutReps = False
            model = AsyncConnection.Session.RetrieveModelWithOpts(mdlDescr, options)
            print(model.GetParam(para_content['name']))
            if model.GetParam(para_content['name']):

                model.GetParam(para_content['name']).Delete()
            model.CreateParam(para_content['name'], ipara_content['value'])
            model.save()
            st_message.insert('end', "文件：" + model.Filename + '\t' + "参数：" + para_content['name'] + '\t' + "已添加" + '\n')
            win.update()
        #AsyncConnection.End()
        messagebox.showinfo('提示', '参数已全部添加')
    except Exception:
        messagebox.showinfo('提示', '参数添加失败')
    finally:
        if 'AsyncConnection' in locals().keys():
            if AsyncConnection.IsRunning():
                AsyncConnection.End()


#删除参数

def del_para():
    try:
        cAC =client.Dispatch(VBAPI.CCpfcAsyncConnection)
        AsyncConnection = cAC.Start(CREO_APP + ' -g:no_graphics -i:rpc_input', '')
        files = AsyncConnection.Session.ListFiles("*.prt", getattr(VBAPI.constants, "EpfcFILE_LIST_LATEST"), INPUT_DIR)
        for i in range(0, files.Count):
            ModelDescriptor = client.Dispatch(VBAPI.CCpfcModelDescriptor)
            mdlDescr = ModelDescriptor.Create(getattr(VBAPI.constants, 'EpfcMDL_PART'), "", None)
            mdlDescr.Path = files.Item(i)
            RetrieveModelOptions = client.Dispatch(VBAPI.CCpfcRetrieveModelOptions)
            options = RetrieveModelOptions.Create()
            options.AskUserAboutReps = False
            model =AsyncConnection.Session.RetrieveModelWithOpts(mdlDescr, options)
            parameter = model.GetParam(e_paraname.get())
            if parameter != None:
                parameter.Delete()
                model.save()
                st_message.insert('end', "文件：" + model.Filename + '\t' + " 参数：" + e_paraname.get() + '\t' + "已删除" + '\n')
                win.update()
        messagebox.showinfo('提示', '参数已全部删除')
    except ValueError:
        messagebox.showinfo('提示', '参数删除失败')
    finally:
        if 'AsyncConnection' in locals().keys():
            if AsyncConnection.IsRunning():
                AsyncConnection.End()

#选择Creo程序路径
def chooseapp():
    filename = filedialog.askopenfilename()
    if filename != '':
        CREO_APP = filename
        e1.delete('0', 'end')
        e1.insert('0', CREO_APP)

#选择目录
def choosedir():
    dirname = filedialog.askdirectory()
    if dirname !='':
        INPUT_DIR = dirname
        e2.delete('0', 'end')
        e2.insert('0', INPUT_DIR)


Button(win, text="选择文件", command=chooseapp).grid(row=0, column=5, padx=5, pady=5)
Button(win, text="选择目录", command=choosedir).grid(row=1, column=5, padx=5, pady=5)
Button(win, text="添加/修改参数", command=add_para).grid(row=4, column=0, padx=5, pady=5)
Button(win, text="删除参数", command=del_para).grid(row=4, column=1, padx=5, pady=5)
#Button(win, text="修改参数", command=mod_para).grid(row=4, column=2, padx=5, pady=5)


win.mainloop()




